package com.pwc.conversionTool.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;

import javax.servlet.ServletContext;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.pwc.conversionTool.csv.CsvUpload;

@Controller
public class CsvController {
	// log 4j
	private static final Logger logger = LoggerFactory
			.getLogger(CsvController.class);

	@Autowired
	public ServletContext context;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/csv/upload", method = RequestMethod.GET)
	public String upload(Locale locale, Model model) {
		return "csv/upload";
	}

	@RequestMapping(value = "/csv/multipleUpload", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		return "csv/multipleUpload";
	}

	@RequestMapping(value = "/csv/uploadFileView", method = RequestMethod.GET)
	public String uploadFileView(Locale locale, Model model)
			throws DocumentException {
		return "csv/uploadFileView";
	}

	/**
	 * 
	 * @param fileName
	 * @param file
	 * @param locale
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/csv/upload", method = RequestMethod.POST)
	public String uploadProcess(@RequestParam("fileName") String fileName,
			@RequestParam("file") MultipartFile file, @RequestParam("path")String path,
			Locale locale, Model model) {
		String message = "";
		if (!file.isEmpty()) {
			try {
				new CsvUpload(context).uploadSingleFile(file, fileName,
						path);
				message = "upload success!";
			} catch (Exception e) {
				message = " failed to upload " + e.getMessage();
				
				logger.error("log4j is running in soapSecurity");
				logger.error(Arrays.toString(e.getStackTrace()));
			}
		} else {
			message = " failed to upload , because the file was empty.";
		}
		model.addAttribute("msg", message);
		return "csv/upload";
	}

	@RequestMapping(value = "/csv/multipleUpload", method = RequestMethod.POST)
	public String getMutiuploadFile(
			@RequestParam("file") MultipartFile[] files,String path, Locale locale,
			 Model model) {
		String message = "";
		if (files.length != 0) {
			try {
				new CsvUpload(context).uploadMutiFile(files, path);
			} catch (Exception e){			
				logger.error("error in multipleUpload");				
				logger.error(Arrays.toString(e.getStackTrace()));
			}
			message = "upload success";
		} else {
			message = "failed to upload , because the file was empty.";
		}

		model.addAttribute("msg", message);

		return "csv/multipleUpload";
	}

}
